package com.yingxin.yxerp.module.inform.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yx.framework.security.user.UserSupport;
import com.yingxin.yxerp.module.inform.constant.InformType;
import com.yingxin.yxerp.module.inform.entity.InformWork;
import com.yingxin.yxerp.module.inform.entity.builder.InformWorkBuilder;
import com.yingxin.yxerp.module.inform.mapper.InformWorkMapper;
import com.yingxin.yxerp.module.inform.service.IInformWorkService;
import com.yingxin.yxerp.module.inform.service.IInformerSetService;
import com.yingxin.yxerp.module.inform.vo.req.InformWorkCreateVo;
import com.yingxin.yxerp.module.inform.vo.resp.InformWorkRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 工作通知 服务实现类
 * </p>
 *
 * @author dongpengfei
 * @since 2021-12-10
 */
@Service
public class InformWorkServiceImpl extends ServiceImpl<InformWorkMapper, InformWork> implements IInformWorkService {

    @Autowired
    private IInformerSetService informerSetService;

    @Autowired
    private UserSupport userSupport;


    /**
     * 查询全部
     *
     * @param
     * @return
     */
    @Override
    public List<InformWorkRespVo> listVo() {
        List<InformWorkRespVo> informWorkRespVos = baseMapper.listVo(userSupport.getUserId());
        return informWorkRespVos;
    }


    /**
     * 创建通知
     *
     * @param informType
     * @param informId
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void startInform(InformType informType, String informId, String remark) {
        InformWorkCreateVo createVo = new InformWorkCreateVo();
        createVo.setInformType(informType.getType());
        createVo.setInformId(informId);
        createVo.setContent(remark.length() > 10 ? remark.substring(0, 10) + "..." : remark);
        InformWork informWork = InformWorkBuilder.build(createVo);
        List<String> informerIdList = informerSetService.getInformerIdList(informType.getType());
        if (CollectionUtil.isEmpty(informerIdList)){
            throw new BizException("请在系统设置字典表中设置提醒通知人!");
        }
        for (String informerId : informerIdList) {
            informWork.setInformerId(informerId);
            save(informWork);
        }
    }

    @Override
    public List<InformWorkRespVo> getByInformId(String informId) {
        return baseMapper.getByInformId(informId);
    }
}
